package nccloud.fct.ap.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.pub.BusinessException;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

/**
 * 查询付款合同的累计原币付款金额接口
 *
 * @author ouyanggx
 * @date 2025-10-24
 * */
public class FctApPayMnyQueryList extends HttpServlet implements IHttpServletAdaptor {

    private IUAPQueryBS uapQueryBS = NCLocator.getInstance().lookup(IUAPQueryBS.class);

    @Override
    public void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");/** 设置请求编码 */
        response.setContentType("text/html");/** 设置响应类型 */
        response.setCharacterEncoding("UTF-8");/** 设置响应编码 */

        loginNcSystem();// 模拟登录

        JSONObject returnJson = new JSONObject();

        try {
            JSONObject reqJson = JSONObject.parseObject(readRequest(request));

            // 指定数据源
            String dataSource = reqJson.getString("datasource");
            if (StringUtils.isBlank(dataSource)) {
                throw new Exception("datasource参数不能为空");
            }
            InvocationInfoProxy.getInstance().setUserDataSource(dataSource);
            InvocationInfoProxy.getInstance().setGroupId("0001A210000000000JB9");

            JSONArray ids = reqJson.getJSONArray("ids");
            JSONObject data = new JSONObject();
            if (ids != null && ids.size() > 0) {
                List<Map<String, Object>> queryResult = doQueryPayMny(ids.toArray(new String[ids.size()]));
                if  (queryResult != null && queryResult.size() > 0) {
                    for (Map<String, Object> result : queryResult) {
                        data.put((String)result.get("vbillcode"), result.get("norigpshamount"));
                    }
                }
            }

            returnJson.put("code", "200");
            returnJson.put("message", "success");
            returnJson.put("data", data);
        } catch (Exception e) {
            returnJson.put("code", "200");
            returnJson.put("message", e.getMessage());
        }

        response.getWriter().print(returnJson);
    }

    /**
     * 查询付款合同的合同编码及累计原币付款金额
     * */
    private List<Map<String, Object>> doQueryPayMny(String[] ids) throws BusinessException {
        String sql = " select vbillcode,sum(norigpshamount) norigpshamount from fct_ap " +
                " where nvl(dr,0)=0 and fstatusflag='1' " +
                " and vbillcode in ('" + String.join("','", ids) + "') " +
                " group by vbillcode ";
        return (List<Map<String, Object>>) uapQueryBS.executeQuery(sql, new MapListProcessor());
    }

    /**
     * 从request中获取接口数据
     * @param request 接口请求
     * */
    private String readRequest(HttpServletRequest request) throws Exception {
        InputStreamReader insr = new InputStreamReader(request.getInputStream(), "utf-8");
        StringBuffer result = new StringBuffer();
        int respInt = insr.read();
        while (respInt != -1) {
            result.append((char) respInt);
            respInt = insr.read();
        }
        if (result.length() < 1) {
            throw new BusinessException("未获取到请求体信息，请检查！");
        }
        return result.toString();
    }

    /**
     * 登录nc系统
     */
    private void loginNcSystem() {
        NCLocator.getInstance().lookup(ISecurityTokenCallback.class)
                .token("NCSystem".getBytes(), "pfxx".getBytes());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        throw  new UnsupportedOperationException("Not supported get.");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doAction(req, resp);
    }

}
